package com.it.you.base.bigdecimal;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;

/**
 * 比较大小
 */
public class BigDecimalTest1 {
    public static void main(String[] args) {

        BigDecimal groupBuyNum = new BigDecimal("12");
        BigDecimal userGroupRemainNum = new BigDecimal("10");
        if (groupBuyNum.compareTo(userGroupRemainNum) > 0) {
            System.out.println("超限购了");
        }

        BigDecimal settlementPrice = new BigDecimal("0");
        if (settlementPrice.compareTo(BigDecimal.ZERO) <= 0) {
            System.out.println("金额不能小于等于0");
        }
        System.out.println("----------------------------------------------");
        //百分号保留
        BigDecimal totalPrice = new BigDecimal("0");
        BigDecimal divide = settlementPrice.compareTo(BigDecimal.ZERO) == 0? new BigDecimal("0.000").multiply(new BigDecimal("100")) :
                totalPrice.divide(settlementPrice,3, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
        System.out.println("divide = " + divide);
        System.out.println("----------------------------------------------");
        BigDecimal total = new BigDecimal("0.00");
        System.out.println(total.compareTo(BigDecimal.ZERO) == 0);
        System.out.println("----------------------------------------------");
        //返回商和余数
        BigDecimal buyNum = new BigDecimal("12");
        BigDecimal minStep = new BigDecimal("7");
        System.out.println(Arrays.toString(buyNum.divideAndRemainder(minStep)));//[1, 5]
        System.out.println("商数：" + buyNum.divideAndRemainder(minStep)[0]);
        System.out.println("余数：" + buyNum.divideAndRemainder(minStep)[1]);
        System.out.println("----------------------------------------------");
        //计算 BigDecimal 小数部分的位数
        System.out.println(checkDecimalCount(new BigDecimal("12.02")));

        //得到 BigDecimal 小数部分
        BigDecimal decimal = new BigDecimal("6.6");
        BigDecimal remainder = decimal.remainder(BigDecimal.ONE);
        System.out.println("小数部分是：" + remainder);
        System.out.println(remainder.remainder(BigDecimal.ONE));
        System.out.println("----------------------------------------------");
        //和0比较
        BigDecimal buy = new BigDecimal("0.0001");
        if (buy.compareTo(BigDecimal.ZERO) > 0) {
            System.out.println("大于0");
        } else if (buy.compareTo(BigDecimal.ZERO) < 0) {
            System.out.println("小于0");
        }else {
            System.out.println("等于0");
        }

    }


    //计算 BigDecimal 小数部分的位数
    public static String checkDecimalCount(BigDecimal bigDecimal) {
        String decimalStr = bigDecimal.remainder(BigDecimal.ONE).stripTrailingZeros().toPlainString();
        int i = decimalStr.indexOf(".");
        int decimalCount;
        if (i < 0) {
            decimalCount = 0;
        } else {
            decimalCount = decimalStr.length() - 1 - i;
        }
        return "小数位数为：" + decimalCount;
    }
}
